#include "pwm.h"

extern void initPWM(int freq)
{
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER3);
	ROM_TimerConfigure(TIMER3_BASE, TIMER_CFG_PERIODIC);

	_period = (ROM_SysCtlClockGet() / freq);

	ROM_TimerIntEnable(TIMER3_BASE, TIMER_TIMA_TIMEOUT);
	ROM_IntEnable(INT_TIMER3A);
	ROM_TimerEnable(TIMER3_BASE, TIMER_A);
}

extern void pwmHandler(void)
{
	//clear interrupts
	ROM_TimerIntClear(TIMER3_BASE, TIMER_TIMA_TIMEOUT);
	_onOff ^= 0xff;

	//first run, time = duty, second run, time = period - duty
	(_onOff) ? ROM_TimerLoadSet(TIMER3_BASE, TIMER_A, _duty) : ROM_TimerLoadSet(TIMER3_BASE, TIMER_A, _period-_duty);

	//write out state
	ROM_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, _onOff);
}

extern void pwmSetDuty(int duty_cycle)
{
	if(duty_cycle > 1000)
	{
		duty_cycle = 1000;
	}
	duty_cycle = duty_cycle*_period;
	_duty = duty_cycle/1000;
}

